package com.by.application;

/**
 * @version 1.0
 * @Author 彭彦彬
 * @Date 2025/4/8 20:19
 * @注释
 */
import com.by.annotion.Component;
import com.by.bean.BeanDefinition;
import com.by.factory.SimpleBeanFactory;

import java.io.File;
import java.net.URL;
import java.util.Objects;

public class AnnotationConfigApplicationContext extends SimpleBeanFactory {
    public AnnotationConfigApplicationContext(String basePackage) throws Exception {
        scan(basePackage);
    }

    private void scan(String basePackage) throws Exception {
        String packagePath = basePackage.replace(".", "/");
        URL url = getClass().getClassLoader().getResource(packagePath);
        if (url == null) {
            throw new IllegalArgumentException("Package not found: " + basePackage);
        }

        File dir = new File(url.getFile());
        for (File file : Objects.requireNonNull(dir.listFiles())) {
            String className = file.getName().replace(".class", "");
            Class<?> clazz = Class.forName(basePackage + "." + className);
            if (clazz.isAnnotationPresent(Component.class)) {
                Component component = clazz.getAnnotation(Component.class);
                String beanName = component.value().isEmpty() ? clazz.getSimpleName() : component.value();
                registerBeanDefinition(beanName, new BeanDefinition(clazz));
            }
        }
    }
}